package com.tiange.tgrandomcode.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.tiange.tgrandomcode.Utils.ExcelBindingHeaderUtils;
import com.tiange.tgrandomcode.entity.RandomCode;
import com.tiange.tgrandomcode.service.RandomCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 随机码控制层
 */
@RestController
@Slf4j
@RequestMapping("/random")
public class RandomController {
    @Autowired
    private RandomCodeService randomCodeService;

    /**
     * 导入随机码表
     */
    @RequestMapping("/import")
    public void importOrderStatistic(@RequestBody MultipartFile file, HttpServletResponse response) {
        try {
            log.info("进入导入随机码接口");
            InputStream in = file.getInputStream();
            //io流给ExcelReader
            ExcelReader excelReader = ExcelUtil.getReader(in);
            //映射下单统计表实体类字段
            ExcelBindingHeaderUtils.bindingRandomCode(excelReader);
            //存入所有的excel数据
            List<RandomCode> randomCodeList = excelReader.readAll(RandomCode.class);

            String fileName = StrUtil.format("天哥随机码{}.xlsx", DateTime.now().toString("yyyyMMdd"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(URLEncoder.encode(fileName, "UTF-8")));
            this.randomCodeService.exportRandomCode(response.getOutputStream(), randomCodeList);
        } catch (IOException ex) {
            log.error("随机码异常：{}", this.getClass());
            throw new RuntimeException(ex);
        }
    }
}
